package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Value("${SMSUtils.signName}")
    private String signName;
    @Value("${SMSUtils.templateCode}")
    private String templateCode;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param user
     */
    @Override
    public void sendMsg(User user, HttpSession session) {
        // 获取用户发送的电话号码
        String phone = user.getPhone();

        // 调用工具类产生随机验证码(4-6位的验证码),转为字符串形式
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        log.info("随机验证码:{}",code);
        // 会话技术,将电话和验证码存入域中
        //session.setAttribute(phone,code);

        // 项目优化: 不再将验证码存入session中;而是将验证码存入redis缓存中,并设置存活时间5分钟
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

        // 调用工具类发送验证码(短信名称,短信内容,电话号码,验证码)
        //SMSUtils.sendMessage(signName,templateCode,phone,code);
    }

}
